import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Image,
  Tag,
  Space,
  Modal,
  message,
} from 'antd'
import { Link } from 'react-router-dom'
import { ArticleListState, articleStatus } from 'api/contants'
import { getArticleList, DelArticleList } from 'api/article'
import defalustImg from 'assets/error.png'
import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import MyChannel from 'components/MyChannel'

const { RangePicker } = DatePicker
const { confirm } = Modal
export default class ArticleList extends Component {
  // 存储用户筛选条件的变量
  params = {}
  state = {
    currentPage: 1,
    pageSize: 10,
    articles: [],
    total: 0,
    isLoading: false,
  }
  // 表格列数据
  columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render(value, rowItem, index) {
        const { type, images } = value
        if (type === 0) {
          //  无图
          return (
            <Image
              width={200}
              height={150}
              src={defalustImg}
              preview={false}
            ></Image>
          )
        } else {
          // 单图 / 多图 只展示第一张
          return (
            <Image
              width={200}
              height={150}
              src={images[0]}
              fallback={defalustImg}
            ></Image>
          )
        }
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (data) => {
        const tagObj = articleStatus[data]
        return <Tag color={tagObj.color}>{tagObj.text}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (value, rowItem, index) => {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => this.handleEdit(rowItem.id)}
            ></Button>
            <Button
              onClick={() => this.handleDeLClick(rowItem.id)}
              type="primary"
              shape="circle"
              danger
              icon={<DeleteOutlined />}
            ></Button>
          </Space>
        )
      },
    },
  ]

  render() {
    const { articles, total, currentPage, pageSize, isLoading } = this.state

    return (
      <div className="articleList">
        {/* 筛选盒子 */}
        <Card
          // 面包屑导航
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/layout">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>内容管理</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          {/* 顶部表单 */}
          <Form onFinish={this.onFinish} initialValues={{ status: undefined }}>
            <Form.Item label="状态" name="status">
              <Radio.Group>
                {ArticleListState.map((item, index) => (
                  <Radio key={index} value={item.id}>
                    {item.name}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            <Form.Item label="频道" name="channel_id">
              <MyChannel></MyChannel>
            </Form.Item>
            <Form.Item label="日期" name="date">
              <RangePicker></RangePicker>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>

        {/* 表格盒子 */}
        <Card title={`根据筛选,共查询到${total} 条数据`}>
          <Table
            dataSource={articles}
            columns={this.columns}
            rowKey="id"
            isLoading={false}
            pagination={{
              position: ['bottomCenter'],
              current: currentPage,
              pageSize: pageSize,
              total: total,
              onChange: this.changePage,
            }}
          ></Table>
        </Card>
      </div>
    )
  }
  //  页面更新时发送请求
  componentDidMount() {
    this.getAllArticleList()
  }
  // 动态路由传参
  handleEdit = (id) => {
    this.props.history.push(`/layout/publish/${id}`)
  }
  // 获取所有文章列表数据
  async getAllArticleList() {
    // 不能直接使用 需解构
    const { pageSize, currentPage, isLoading } = this.state
    this.setState({
      isLoading: true,
    })
    const { data } = await getArticleList({
      page: currentPage,
      per_page: pageSize,
      // ...this.params,
    })
    this.setState({
      articles: data.results,
      total: data.total_count,
      currentPage: data.page,
      pageSize: data.per_page,
      isLoading: false,
    })
  }

  // 表格分页
  changePage = (page, pageSize) => {
    this.setState(
      {
        currentPage: page,
        pageSize: pageSize,
        articles: [],
      },
      () => {
        this.getAllArticleList()
      }
    )
  }
  //  获取所有表单数据
  onFinish = (values) => {
    // console.log(values)
    // 状态的处理
    // if (values.status !== -1) {
    this.params.status = values.status
    // } else {
    //   delete this.params.status
    // }
    // 频道的处理
    // if (values.channel_id !== undefined) {
    // axios 会屏蔽掉 类似 undefined null 之类的传值 对后台没有影响
    this.params.channel_id = values.channel_id
    // }
    // 处理日期
    this.params.begin_pubdate =
      values.date && values.date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss')
    this.params.end_pubdate =
      values.date && values.date[1].startOf('day').format('YYYY-MM-DD HH:mm:ss')
    this.getAllArticleList()
    // console.log(values)
    // console.log(this.params)
  }
  // 删除 文章
  handleDeLClick = (id) => {
    confirm({
      title: '提示: ',
      icon: <ExclamationCircleOutlined />,
      content: '确认删除吗',
      onOk: async () => {
        await DelArticleList(id)
        this.getAllArticleList()
        message.success('删除成功')
      },
      onCancel() {
        console.log('Cancel')
      },
    })
  }
}
